package com.dc.pay.service;


import com.alibaba.fastjson.JSONObject;
import com.dc.base.BaseApiService;
import com.dc.base.BaseResponse;
import com.dc.pay.factory.StrategyFactory;
import com.dc.pay.mapper.PaymentChannelMapper;
import com.dc.pay.mapper.entity.PaymentChannelEntity;
import com.dc.pay.out.dto.PayMentTransactionDto;
import com.dc.pay.strategy.IPayStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: KEYD
 * @Date: 2020/1/12 11:58
 * @Desc: 实现支付接口
 */
@RestController
public class PayContextServiceImpl extends BaseApiService<JSONObject> implements IPayContextService {

    @Autowired
    private PaymentChannelMapper paymentChannelMapper;

    @Autowired
    private IPayMentTransacInfoService payMentTransacInfoService;

    @Override
    public BaseResponse<JSONObject> payToHtml(@RequestParam("channelId") String channelId, @RequestParam("payToken") String payToken) {
        //1、使用渠道Id获取渠道信息 class_address
        PaymentChannelEntity paymentChannel = paymentChannelMapper.selectBychannelId(channelId);
        if (paymentChannel == null) {
            return setResultError("没有查询到该渠道的信息");
        }
        //2、使用 paytoken 令牌 获取支付参数
        BaseResponse<PayMentTransactionDto> tokenByPayMentTransac = payMentTransacInfoService.tokenByPayMentTransaction(payToken);
        if (!isSuccess(tokenByPayMentTransac)) {  // !=200
            return setResultError(tokenByPayMentTransac.getMsg());
        }

        PayMentTransactionDto payMentTransacDTO = tokenByPayMentTransac.getData(); //根据Token查询支付信息
        //3、执行具体的支付渠道的算法获取不同的html表单数据  策略设计模式  java 反射执行
        String classAddress = paymentChannel.getClassAddres();//类的完整地址
        //4、直接返回html
        IPayStrategy payStartegy = StrategyFactory.getPayStartegy(classAddress);  //具体的支付策略
        String payHtml = payStartegy.toPayHtml(paymentChannel, payMentTransacDTO);

        JSONObject data = new JSONObject();
        data.put("payHtml", payHtml);
        return setResultSuccess(data);
    }
}
